package com.combetter.changxing.viewmodel;

import android.app.Application;
import android.content.Intent;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.combetter.changxing.MyApp;
import com.combetter.changxing.R;
import com.combetter.changxing.db.entity.User;
import com.combetter.changxing.model.parameter.RegisterParameter;
import com.combetter.changxing.net.service.APIService;
import com.combetter.changxing.ui.activity.MainActivity;
import com.combetter.changxing.ui.activity.RegisterActivity;
import com.combetter.changxing.ui.dialog.AgeLimitDialog;
import com.combetter.changxing.ui.dialog.BelowSelectDialog;
import com.combetter.changxing.ui.dialog.CityListDialog;
import com.combetter.changxing.ui.dialog.LoadingDialog;
import com.combetter.changxing.ui.fragment.RegisterNextFragment;
import com.combetter.changxing.util.AppManager;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.FragmentUtils;
import com.combetter.changxing.util.LogUtil;
import com.combetter.changxing.util.RegUtils;
import com.combetter.changxing.util.RxUtil;
import com.combetter.changxing.util.ToastUtils;
import com.combetter.changxing.viewmodel.base.BaseViewModel;

import java.util.ArrayList;
import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.combetter.changxing.constanst.Constants.REUEST_CODDE;

/**
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/6.
 */
public class RegisterViewModel extends BaseViewModel {

    //性别Id
    public static int sexId = 6;
    //手机号码
    public ObservableField<String> userName = new ObservableField<>("");
    //城市
    public ObservableField<String> city = new ObservableField<>("");
    //验证码
    public ObservableField<String> code = new ObservableField<>("");
    //密码
    public ObservableField<String> password = new ObservableField<>("");
    //确认密码
    public ObservableField<String> password2 = new ObservableField<>("");
    //年龄
    public ObservableField<String> age = new ObservableField<>("");
    //年龄
    public ObservableField<String> sex = new ObservableField<>("");

    //第三方登录昵称
    public static ObservableField<String> nickname = new ObservableField<>("");
    //第三方登录头像
    public static ObservableField<String> figureurl = new ObservableField<>("");
    //第三方登录openId
    public static ObservableField<String> openId = new ObservableField<>("");

    private String savaCode = "";
    public RegisterParameter parameter;


    public RegisterViewModel(@NonNull Application application) {
        super(application);
    }


    public void back(View view) {
        ((RegisterActivity) view.getContext()).finish();
    }


    /**
     * 发送验证码
     */
    public void sendCode(View view) {
        TextView sendCode = (TextView) view;
        if (Check.isEmpty(userName.get())) {
            ToastUtils.error("请输入手机号码");
            return;
        }
        mHttpRequest.createService(APIService.class)
                .sendCode(userName.get(), 1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(httpResult -> {
                    LogUtil.e("注册验证码返回：", httpResult);
                    if (httpResult.getCode() == 200) {
                        LogUtil.e("发送验证码成功 " + httpResult.getData());
                        ToastUtils.success("发送验证码成功" );
                        savaCode = httpResult.getData().toString();
//                        code.set(savaCode);
                        RxUtil.countDown(60).doOnComplete(() -> {
                            sendCode.setEnabled(true);
                            sendCode.setText("发送验证码");
                        }).subscribe(integer -> {
                            sendCode.setEnabled(false);
                            sendCode.setText("(" + integer + ")重新发送");
                        });
                    } else {
                        ToastUtils.error(httpResult.getMsg());
                    }
                });
    }

    /**
     * 跳转城市列表dialog
     *
     * @param view
     */
    public void startCityList(View view) {
        CityListDialog dialog = new CityListDialog();
        Fragment fragment = FragmentUtils.getTopShowFragment(((RegisterActivity) view.getContext()).getSupportFragmentManager());
        dialog.setTargetFragment(fragment, REUEST_CODDE);
        dialog.show(((RegisterActivity) view.getContext()).getSupportFragmentManager(), "");
    }

    /**
     * 注册
     *
     * @param view
     */
    public void register(View view) {
        if (Check.isEmpty(userName.get())) {
            ToastUtils.error("请输入手机号！");
            return;
        }
        if (!RegUtils.isMobile(userName.get())) {
            ToastUtils.error("手机号码格式不对！");
            return;
        }
        if (Check.isEmpty(code.get())) {
            ToastUtils.error("请输入验证码！");
            return;
        }
        if (!savaCode.equals(code.get())) {
            ToastUtils.error("验证码不正确！");
            return;
        }
        if (Check.isEmpty(city.get())) {
            ToastUtils.error("请选择城市！");
            return;
        }
        if (Check.isEmpty(age.get())) {
            ToastUtils.error("请输入年龄！");
            return;
        }
        if (Integer.valueOf(age.get()) < 18) {
            AgeLimitDialog dialog = new AgeLimitDialog();
            Fragment fragment = FragmentUtils.getTopShowFragment(((RegisterActivity) view.getContext()).getSupportFragmentManager());
            dialog.setTargetFragment(fragment, REUEST_CODDE);
            dialog.show(((RegisterActivity) view.getContext()).getSupportFragmentManager(), "");
            return;
        }
        if (Integer.valueOf(age.get()) > 100) {
            ToastUtils.error("年龄已超过100！");
            return;
        }
        if (Check.isEmpty(sex.get())) {
            ToastUtils.error("请选择性别！");
            return;
        }
        int saveSex = 0;
        if (sex.get().equals("男")) {
            saveSex = 1;
        } else if (sex.get().equals("女")) {
            saveSex = 2;
        }
        parameter = new RegisterParameter(userName.get(), city.get(), age.get(), saveSex + "", figureurl.get(), openId.get(), nickname.get(), code.get());
        RegisterNextFragment nextFragment = new RegisterNextFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("userInfo", parameter);
        nextFragment.setArguments(bundle);
        ((RegisterActivity) view.getContext()).toFragment(R.id.fl_content, nextFragment);
    }

    /**
     * 完成注册
     *
     * @param view
     */
    public void completeRegister(View view) {
        if (Check.isEmpty(password.get())) {
            ToastUtils.error("请输入密码！");
            return;
        }
        if (password.get().length() < 6) {
            ToastUtils.error("密码为6-18位！");
            return;
        }
        if (!password.get().equals(password2.get())) {
            ToastUtils.error("密码不一致！");
            return;
        }
        LoadingDialog dialog = LoadingDialog.getInstance(view.getContext());
        dialog.show();
        HashMap<String, String> map = new HashMap<>();
        if (!Check.isEmpty(parameter.getOpenId())) {
            map.put("openId", parameter.getOpenId());
        }
        if (!Check.isEmpty(parameter.getNickname())) {
            map.put("nick", parameter.getNickname());
        }
        if (!Check.isEmpty(parameter.getSubImages())) {
            map.put("subImages", parameter.getSubImages());
        }
        map.put("phone", parameter.getPhone());
        map.put("password", password.get());
        map.put("sex", parameter.getSex());
        map.put("addressName", parameter.getCity());
        map.put("age", parameter.getAge());
        map.put("code", parameter.getCode());
        map.put("type", "1");

        LogUtil.e("注册参数：", map);
        mHttpRequest.createService(APIService.class)
                .register(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(userHttpResult -> {
                    LogUtil.e("注册返回：" + new Gson().toJson(userHttpResult));
                    if (userHttpResult.getCode() == 200) {
                        login(view, dialog);
                    } else {
                        ToastUtils.error(userHttpResult.getMsg());
                    }
                });

    }

    /**
     * 登录
     */
    private void login(View view, LoadingDialog dialog) {
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", parameter.getPhone());
        map.put("password", password.get());

        LogUtil.e("登录参数：", map);
        mHttpRequest.createService(APIService.class)
                .login(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> dialog.dismiss())
                .subscribe(userHttpResult -> {
                    dialog.dismiss();
                    LogUtil.e("登录返回：" + new Gson().toJson(userHttpResult));
                    if (userHttpResult.getCode() == 200) {
                        LogUtil.e("成功获取信息:" + new Gson().toJson(userHttpResult.getData()));
                        User user = userHttpResult.getData();
                        JPushInterface.setAlias(view.getContext(), 0, user.getUid());
                        MyApp.getInstance().getDatabase().userDao().insertUser(user);
                        view.getContext().startActivity(new Intent(view.getContext(), MainActivity.class));
                        AppManager.finishAllActivity();
                    } else {
                        ToastUtils.error(userHttpResult.getMsg());
                    }
                });
    }

    /**
     * 性别
     *
     * @param view
     */
    public void setSex(View view) {
        ArrayList<String> list = new ArrayList<>();
        list.add("男");
        list.add("女");
        BelowSelectDialog dialog = new BelowSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("mOptionsItems", list);
        bundle.putInt("titleId", sexId);
        dialog.setArguments(bundle);
        Fragment fragment = FragmentUtils.getTopShowFragment(((RegisterActivity) view.getContext()).getSupportFragmentManager());
        dialog.setTargetFragment(fragment, REUEST_CODDE);
        dialog.show(((RegisterActivity) view.getContext()).getSupportFragmentManager(), "");
    }
}
